<?php 

import('@.com.99ebc.lib.Error');
import('@.com.99ebc.lib.File');
import('@.com.99ebc.lib.Xml');

import("ORG.Util.Image");

class ProducttypeModel extends Model {

    //表字段配置
    protected $fields   = array(
                                'producttype_id',
                                'producttype_name',
                                'sort_loc',
                                'edit_time',
                                '_pk' => 'producttype_id',
                                '_autoinc' => true
                            );

    
    //自动验证
    protected $_validate    = array(
        array('producttype_name', 'require', '名称不能为空！'),
        array('sort_loc', 'number', '排序编号必须是数字！',2)
    );

    //自动完成
    protected $_auto        = array(
        array('edit_time', 'mktime', 3, 'function')
    );

    //对应的产品类
    private $_product;

    protected static $orderFields = 'sort_loc';

    protected static $xmlFields   = 'producttype_id, producttype_name';

    protected $_countWhere;

    protected $_error;

    //XML配置参数
    protected static $xmlFilePath   = 'xml/producttype.xml';

    protected static $childNode     = '
<link type="photo">
    <name><![CDATA[<b>%s</b>]]></name>
    <asset>products_show/products_show.swf</asset>
</link>';
    protected static $rootNode     = '
<menu>
    %s
</menu>';


    public function __construct() {
        parent::__construct();

        $this->_countWhere  = '';
        $this->_product     = null;
        $this->_error       = new Error(); 
    }

    //得到记录总数
    public function getCountRecords() {
        return $this->where($this->_countWhere)->count();
    }
    
    //搜索方法
    public function searchProducttype($page = 0, $keyword, $perPage = 10) {
        if(preg_match('/^\/+\d+$/', $keyword)) {
            $whereSearch  = '`producttype_id` = ' . strtr($keyword, array('/' => ''));
        } else {
            $whereSearch  = '`producttype_name` like \'%' . $keyword . '%\'';
        }
        $this->_countWhere  = $whereSearch;

        return $this->seeProducttype($page, $whereSearch, $perPage);
    }

    //查看列表方法 
    public function seeProducttype($page = 0, $whereProducttype = '', $perPage = 10) {
        return $this->where($whereProducttype)->order(self::$orderFields)->limit($perPage)->page($page)->select();
    }

    //查看列表方法 
    public function seeallProducttype($whereProducttype = '') {
        return $this->field('`producttype_id`,`producttype_name`')->where($whereProducttype)->order(self::$orderFields)->select();
    }


    //查看记录详细信息方法
    public function infoProducttype($recordId) {
        $record     = $this->where('`producttype_id` = ' . $recordId)->find();
        
        return $record;
    }

    //编辑记录方法
    public function editProducttype($recordId) {
        
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->save()) {
            return $this->getError();
        }

        return true;
    }

    //添加记录方法
    public function addProducttype() {
        
        if(false === $this->create()) {
            return $this->getError();
        }
        if(false === $this->add()) {
            return false;
            return $this->getError();
        }

        return true;
    }

    //删除记录方法
    public function deleteProducttype($recordId) {
        return $this->quickDeleteProducttype(array($recordId));
    }

    //快捷操作：删除记录
    public function quickDeleteProducttype(array $recordIds){
        $whereStr   = $this->genWhereIn('producttype_id', $recordIds);

        return $this->where($whereStr)->delete();
    }

    //生成FLASH调用的XML文件
    public function xmlProducttype() {
        $perPage        = 10;
        $totalRows      = $this->getCountRecords();
        $totalPage      = ceil($totalRows / $perPage);
        for($page = 0; $page < $totalPage; $page ++) {
            $recordList     = $this->getXmlRecordList($page, $perpage);
            $xmlContent     .= $this->genXmlContent($recordList);
        }
        if(false === $this->writeXml($xmlContent)) {
            Logger::log('写入XML内容失败！' . __CLASS__);
            return false;
        }

        return true;
    }

    //得到XML的数据集
    protected function getXmlRecordList($page, $perpage = 10) {
        return $this->field(self::$xmlFields)->order(self::$orderFields)->page($page, $perpage)->select();
    }

    //写入XML文件内容
    protected function writeXml($xmlContent) {
        $xmlContent     = sprintf(self::$rootNode, $xmlContent);
        $xml    = new Xml(self::$xmlFilePath, $xmlContent);

        return  $xml->save();

    }

    //生成主页的XML内容
    protected function genXmlContent($recordList) {
        if(empty($recordList)) {
            return '';
        }
        foreach($recordList as $record) {
            $xmlContent .= vsprintf(self::$childNode, $record['producttype_name']);
            $this->genProductXmlContent($record['producttype_id']);
        }

        return $xmlContent;
    }

    //生成当前产品类型把对应的所有产品XML文件信息
    protected function genProductXmlContent($producttypeId) {
        if(empty($producttypeId)) {
            return false;
        }
        $this->_product     = $this->getProductObject();
        if(true == $this->_product->xmlProduct($producttypeId)) {
            Logger::log("生成产品类型：" . $producttypeId . "对应的产品XML信息成功！");
            return true;
        }
        
        Logger::log("生成产品类型：" . $producttypeId . "对应的产品XML信息失败！");
        return false;
    }

    //得到产品对象
    protected function getProductObject() {
        if(!empty($this->_product)) {
            return $this->_product;
        }

        return D('Product');
    }

    //生成WhereIn条件语句
    protected function genWhereIn($field, array $values) {
        return '`' . $field . '` IN (' . implode(',', $values) . ', -1)';
    }

    //这个将会作为一个interface
    protected function deleteFile($filePath) {
        if(!empty($filePath)) {
            $this->delThumbImageFile($filePath);
            return LittleTools::deleteFile($filePath, $this->_uploadDir);
        }

        return true;
    }

    public function getUploadDir() {
        return '';
    }

}

?>
